#include "DlgReportRent.h"
#include <wx/sizer.h>
#include <wx/statbox.h>
#include <wx/stattext.h>
#include <wx/msgdlg.h>
//wxFreeChart头文件
#include "wx/wxfreechartdefs.h"
#include <wx/xy/xyplot.h>
#include <wx/xy/xylinerenderer.h>
#include <wx/xy/xysimpledataset.h>
#include <wx/axis/logarithmicnumberaxis.h>
#include <wx/multiplot.h>
#include "TimeSeriesDataset.h"
//(*InternalHeaders(DlgUser)
#include <wx/intl.h>
#include <wx/string.h>
//*)

//(*IdInit(DlgUser)
//*)
const wxString CDlgReportRent::TABLENAME=_T("rent");
const wxString WINDOWS_TEXT = _T("房租报表");

//控件ID
const long CDlgReportRent::IDC_BTN_EXIT= wxNewId();
const long CDlgReportRent::IDC_BTN_SEARCH= wxNewId();
const long CDlgReportRent::IDC_COMBO_SEARCH= wxNewId();
const long CDlgReportRent::IDC_EDIT_SEARCH= wxNewId();
const long CDlgReportRent::IDC_LIST= wxNewId();
const long CDlgReportRent::IDC_YEARFROM= wxNewId();
const long CDlgReportRent::IDC_MONTHFROM= wxNewId();
const long CDlgReportRent::IDC_YEARTO= wxNewId();
const long CDlgReportRent::IDC_MONTHTO= wxNewId();
const long CDlgReportRent::IDC_EDIT_STATIC= wxNewId();
const long CDlgReportRent::IDC_PIC= wxNewId();
const long CDlgReportRent::IDC_TIMER_SEC= wxNewId();

BEGIN_EVENT_TABLE(CDlgReportRent,wxDialog)
END_EVENT_TABLE()

CDlgReportRent::CDlgReportRent(wxWindow* parent,wxWindowID id,const wxPoint& pos,const wxSize& size)
    :m_Sectimer(this,IDC_TIMER_SEC)
{
    //(*Initialize(DlgUser)
    Create(parent, id, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE|wxMAXIMIZE_BOX|wxMINIMIZE_BOX, _T("id"));
    SetClientSize(wxDefaultSize);
    Move(wxDefaultPosition);
    //*)
    SetTitle(WINDOWS_TEXT);
    SetWindowStyle(GetWindowStyle()|wxRESIZE_BORDER|wxCLOSE_BOX|wxMAXIMIZE_BOX|wxMINIMIZE_BOX);
    CreateCtrlAndEvent();
    InitComboBoxAndListCtrl();
}

CDlgReportRent::~CDlgReportRent()
{
    //(*Destroy(DlgUser)
    //*)
}

void CDlgReportRent::CreateCtrlAndEvent()
{
    /////////创建控件并布局
    topSizer_=new wxBoxSizer(wxVERTICAL);//顶层窗口布局,从上到下包含每个了窗口布局
    wxFlexGridSizer *fir_secSize=new wxFlexGridSizer(1,2,0,0);
    fir_secSize->AddGrowableCol(0);
    wxBoxSizer *fir_secSize_l=new wxBoxSizer(wxVERTICAL);

    wxBoxSizer *firSize=new wxBoxSizer(wxHORIZONTAL);
    wxBoxSizer *secSize=new wxBoxSizer(wxHORIZONTAL);
    wxGridSizer *fifSize=new wxGridSizer(2);
    wxStaticBox* staticBox=new wxStaticBox(this,wxID_ANY,wxT("统计信息"));
    wxStaticBoxSizer *sixSize=new wxStaticBoxSizer(staticBox,wxHORIZONTAL);
    wxBoxSizer *bottomSize=new wxBoxSizer(wxHORIZONTAL);
    topSizer_->Add(fir_secSize,0,wxEXPAND|wxALL,0);
    topSizer_->Add(fifSize,10,wxEXPAND|wxALL,0);
    topSizer_->Add(sixSize,3,wxEXPAND|wxALL,0);
    topSizer_->Add(bottomSize,0,wxEXPAND|wxALL,0);

    combo_search_=new wxChoice(this,IDC_COMBO_SEARCH);
    btn_Exit_=new wxButton(this,IDC_BTN_EXIT,_T("退出"));
    btn_Search_=new wxButton(this,IDC_BTN_SEARCH,_T("查询"));
    text_search_=new wxTextCtrl(this,IDC_EDIT_SEARCH,wxEmptyString);
    yearfrom_=new wxComboBox(this,IDC_YEARFROM);
    yearto_=new wxComboBox(this,IDC_YEARTO);
    monthfrom_=new wxComboBox(this,IDC_MONTHFROM);
    monthto_=new wxComboBox(this,IDC_MONTHTO);

    list_=new wxListCtrl(this,IDC_LIST,wxDefaultPosition,wxDefaultSize,wxLC_REPORT|wxLC_SINGLE_SEL);
    text_stat_=new wxTextCtrl(this,IDC_EDIT_STATIC,wxEmptyString,
                              wxDefaultPosition,wxSize(600,100),wxTE_PROCESS_ENTER|wxTE_MULTILINE|wxHSCROLL);
    chartpanel_=new wxChartPanel(this,IDC_PIC,NULL,wxDefaultPosition,wxDefaultSize);
    firSize->Add(new wxStaticText(this,wxID_ANY,_T("从")),0, wxFIXED_MINSIZE|wxALL|wxALIGN_RIGHT,5);
    firSize->Add(yearfrom_,0, wxFIXED_MINSIZE|wxALL|wxALIGN_CENTER,5);
    firSize->Add(new wxStaticText(this,wxID_ANY,_T("年")),0, wxFIXED_MINSIZE|wxALL|wxALIGN_RIGHT,5);
    firSize->Add(monthfrom_,0, wxFIXED_MINSIZE|wxALL|wxALIGN_CENTER,5);
    firSize->Add(new wxStaticText(this,wxID_ANY,_T("月")),0, wxFIXED_MINSIZE|wxALL|wxALIGN_RIGHT,5);
    firSize->Add(new wxStaticText(this,wxID_ANY,_T("到")),0, wxFIXED_MINSIZE|wxALL|wxALIGN_RIGHT,5);
    firSize->Add(yearto_,0, wxFIXED_MINSIZE|wxALL|wxALIGN_LEFT,5);
    firSize->Add(new wxStaticText(this,wxID_ANY,_T("年")),0, wxFIXED_MINSIZE|wxALL|wxALIGN_RIGHT,5);
    firSize->Add(monthto_,0, wxFIXED_MINSIZE|wxALL|wxALIGN_LEFT,5);
    firSize->Add(new wxStaticText(this,wxID_ANY,_T("月")),1, wxFIXED_MINSIZE|wxALL|wxALIGN_RIGHT,5);
    secSize->Add(new wxStaticText(this,wxID_ANY,_T("查询类别")),1, wxTILE|wxALL|wxALIGN_RIGHT,5);
    secSize->Add(combo_search_,1, wxEXPAND|wxALL|wxALIGN_CENTER,5);
    secSize->Add(text_search_,1,wxEXPAND|wxALL|wxALIGN_CENTER,5);
    fir_secSize_l->Add(firSize,5,wxFIXED_MINSIZE|wxALL|wxALIGN_CENTER,5);
    fir_secSize_l->Add(secSize,5,wxEXPAND|wxALL,5);
    fir_secSize->Add(fir_secSize_l,10,wxEXPAND|wxALL|wxALIGN_CENTER,0);
    fir_secSize->Add(btn_Search_,0,wxEXPAND|wxALL|wxALIGN_CENTER,0);
    fifSize->Add(list_,1,wxEXPAND | wxALL,5);
    fifSize->Add(chartpanel_,1,wxEXPAND | wxALL,5);
    sixSize->Add(text_stat_,1,wxEXPAND | wxALL,5);

    bottomSize->Add(btn_Exit_,1,wxTILE|wxALL|wxALIGN_CENTER,5);

    SetSizer(topSizer_);//绑定对话框和布局控件
    SetAutoLayout(true);
    topSizer_->Fit(this);//调用对话框大小
    topSizer_->SetSizeHints(this);//设置对话框最小大小

    ///////创建事件
    Connect(IDC_BTN_EXIT,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&CDlgReportRent::OnBnClickedBtnExit);
    Connect(IDC_BTN_SEARCH,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&CDlgReportRent::OnBnClickedBtnSearch);
    Connect( wxEVT_TIMER, (wxObjectEventFunction)&CDlgReportRent::OnTimer);
    m_Sectimer.Start(1000);

    wxLogDebug(_T("CreateCtrl"));
}

void CDlgReportRent::InitComboBoxAndListCtrl()
{
    wxChoice *pchoice=wxDynamicCast(FindWindowById(IDC_COMBO_SEARCH),wxChoice);
    wxListCtrl *pList=wxDynamicCast(FindWindowById(IDC_LIST),wxListCtrl);
    pList->SetSingleStyle(wxLC_REPORT);
    pList->SetSingleStyle(wxLC_SINGLE_SEL);
    const vector<pair<wxString,wxString> >&chs_fileds_name=GetFiled_CHS_Name(_T("name_rent"));
    auto it=chs_fileds_name.cbegin();
    for (; it!=chs_fileds_name.cend(); ++it) {
        wxLogDebug(_T("%s "),it->first);
        pchoice->Append(it->first);
        pList->InsertColumn(pList->GetColumnCount(),it->first,wxLIST_FORMAT_LEFT,wxLIST_AUTOSIZE);
    }
    int year=wxDateTime::Now().GetYear();
    wxComboBox *pchoice_f=wxDynamicCast(FindWindowById(IDC_YEARFROM),wxComboBox);
    wxComboBox *pchoice_t=wxDynamicCast(FindWindowById(IDC_YEARTO),wxComboBox);
    wxString tmp;
    for(int i=-4; i<5; ++i) {//添加年份，前后5年
        tmp.Printf(_T("%d"),year+i);
        pchoice_f->Append(tmp);
        pchoice_t->Append(tmp);
    }
    tmp.Printf(_T("%d"),year);
    pchoice_f->SetValue(tmp);
    pchoice_t->SetValue(tmp);
    pchoice_f=wxDynamicCast(FindWindowById(IDC_MONTHFROM),wxComboBox);
    pchoice_t=wxDynamicCast(FindWindowById(IDC_MONTHTO),wxComboBox);
    for(int i=1; i<13; ++i) {//添加1-12月
        tmp.Printf(_T("%02d"),i);
        pchoice_f->Append(tmp);
        pchoice_t->Append(tmp);
    }
    pchoice_f->SetValue(_T("01"));
    pchoice_t->SetValue(_T("12"));
    wxLogDebug(_T("InitComboBoxAndListCtrl"));
}


void CDlgReportRent::OnBnClickedBtnSearch(wxCommandEvent& event)
{
    wxBusyCursor waticursor;
    wxChoice *pChoice=wxDynamicCast(FindWindowById(IDC_COMBO_SEARCH),wxChoice);
    int index=pChoice->GetSelection();
    wxString strComboTextFirst,strComboTextSecond;
    if (index != wxNOT_FOUND) {
        strComboTextFirst=pChoice->GetString(index);
    }
    wxListCtrl *pList=wxDynamicCast(FindWindowById(IDC_LIST),wxListCtrl);
    pList->DeleteAllItems();
    wxString strYearF,strYearT,strMonthF,strMonthT;//时间参数
    wxComboBox *pBox=wxDynamicCast(FindWindowById(IDC_YEARFROM),wxComboBox);
    strYearF=pBox->GetValue();
    pBox=wxDynamicCast(FindWindowById(IDC_YEARTO),wxComboBox);
    strYearT=pBox->GetValue();
    pBox=wxDynamicCast(FindWindowById(IDC_MONTHFROM),wxComboBox);
    strMonthF=pBox->GetValue();
    pBox=wxDynamicCast(FindWindowById(IDC_MONTHTO),wxComboBox);
    strMonthT=pBox->GetValue();
    if(strYearF.IsEmpty() || strYearT.IsEmpty() || strMonthF.IsEmpty() || strMonthT.IsEmpty()) {
        wxMessageBox(_T("起始年月不能为空"),_T("日期范围有误"),wxOK);
        return;
    }
    const vector<pair<wxString,wxString> >&chs_filed_name=GetFiled_CHS_Name(_T("name_rent"));
    if (chs_filed_name.empty()) {
        return;
    }
    auto it=chs_filed_name.cbegin();
    for (; it!=chs_filed_name.cend(); ++it) {
        if (strComboTextFirst==it->first) {
            strComboTextSecond=it->second;
            break;
        }
    }
    wxString listsql=_T("select rentid,theday,rental,waterqua,waterpri,electricqua,electricpri,total from VrentFull  ")
                     _T(" where (theyear > @pa1 or (theyear =@pa1 and  themonth >=@pa2)) and ")
                     _T(" (theyear < @pa3 or (theyear =@pa3 and  themonth <=@pa4) ) ");
    wxString statsql=_T("select sum(waterpri) as wpri, sum(electricpri) as epri, sum(total) as total from VrentFull  ")
                     _T(" where (theyear > @pa1 or (theyear =@pa1 and  themonth >=@pa2)) and ")
                     _T(" (theyear < @pa3 or (theyear =@pa3 and  themonth <=@pa4) ) ");
    wxTextCtrl *pText=wxDynamicCast(FindWindowById(IDC_EDIT_SEARCH),wxTextCtrl);
    wxString csEditText=pText->GetValue();
    csEditText.Trim(true);
    csEditText.Trim(false);
    if (!csEditText.IsEmpty() && !strComboTextFirst.IsEmpty()) {
        listsql+=_T(" and ")+strComboTextSecond;
        listsql+=_T(" like  '%")+csEditText+_T("%'");
        statsql+=_T(" and ")+strComboTextSecond;
        statsql+=_T(" like  '%")+csEditText+_T("%'");
    }
    wxLogDebug(_T("listsql=%s"),listsql);
    wxLogDebug(_T("statsql=%s"),statsql);
    ////////日常收支查询
    sqlite3_stmt *conStat,*conList;
    if(sqlite3_prepare_v2(g_db,ToDefaultConv(listsql),LenDefaultConv(listsql),&conList,NULL)==SQLITE_OK) {
        int index1 = sqlite3_bind_parameter_index(conList, "@pa1");
        long ltmp;
        strYearF.ToLong(&ltmp);
        if(sqlite3_bind_int(conList, index1, ltmp)!=SQLITE_OK) {
            wxLogDebug(_T("sqlite3_bind_text on m_keyvalue_.first Error on. %s"), sqlite3_errmsg(g_db));
        }
        index1 = sqlite3_bind_parameter_index(conList, "@pa2");
        strMonthF.ToLong(&ltmp);
        if(sqlite3_bind_int(conList, index1, ltmp)!=SQLITE_OK) {
            wxLogDebug(_T("sqlite3_bind_text on m_keyvalue_.first Error on. %s"), sqlite3_errmsg(g_db));
        }
        index1 = sqlite3_bind_parameter_index(conList, "@pa3");
        strYearT.ToLong(&ltmp);
        if(sqlite3_bind_int(conList, index1, ltmp)!=SQLITE_OK) {
            wxLogDebug(_T("sqlite3_bind_text on m_keyvalue_.first Error on. %s"), sqlite3_errmsg(g_db));
        }
        index1 = sqlite3_bind_parameter_index(conList, "@pa4");
        strMonthT.ToLong(&ltmp);
        if(sqlite3_bind_int(conList, index1, ltmp)!=SQLITE_OK) {
            wxLogDebug(_T("sqlite3_bind_text on m_keyvalue_.first Error on. %s"), sqlite3_errmsg(g_db));
        }
        int row_count=0;
        while(sqlite3_step(conList)==SQLITE_ROW) {
            pList->InsertItem(row_count, _T(""));
            pList->SetItem(row_count,0,wxString((const char*)sqlite3_column_text(conList,0), DefaultConv));
            pList->SetItem(row_count,1,wxString((const char*)sqlite3_column_text(conList,1), DefaultConv));
            pList->SetItem(row_count,2,wxString((const char*)sqlite3_column_text(conList,2), DefaultConv));
            pList->SetItem(row_count,3,wxString((const char*)sqlite3_column_text(conList,3), DefaultConv));
            pList->SetItem(row_count,4,wxString((const char*)sqlite3_column_text(conList,4), DefaultConv));
            pList->SetItem(row_count,5,wxString((const char*)sqlite3_column_text(conList,5), DefaultConv));
            pList->SetItem(row_count,6,wxString((const char*)sqlite3_column_text(conList,6), DefaultConv));
            pList->SetItem(row_count++,7,wxString((const char*)sqlite3_column_text(conList,7), DefaultConv));
        }
    } else {
        wxLogDebug(_T("Error on sqlite3_prepare_v2: %s"), sqlite3_errmsg(g_db));
    }
    if (sqlite3_finalize(conList) != SQLITE_OK) {
        wxLogDebug(_T("Error on sqlite3_finalize: %s"), sqlite3_errmsg(g_db));
    }
    //日常收支汇总
    wxString csStat,name;
    double sumexpend=0.,wexpend=0.,eexpend=0.;
    if(sqlite3_prepare_v2(g_db,ToDefaultConv(statsql),LenDefaultConv(statsql),&conStat,NULL)==SQLITE_OK) {
        int index1 = sqlite3_bind_parameter_index(conStat, "@pa1");
        long ltmp;
        strYearF.ToLong(&ltmp);
        if(sqlite3_bind_int(conStat, index1, ltmp)!=SQLITE_OK) {
            wxLogDebug(_T("sqlite3_bind_text on m_keyvalue_.first Error on. %s"), sqlite3_errmsg(g_db));
        }
        index1 = sqlite3_bind_parameter_index(conStat, "@pa2");
        strMonthF.ToLong(&ltmp);
        if(sqlite3_bind_int(conStat, index1, ltmp)!=SQLITE_OK) {
            wxLogDebug(_T("sqlite3_bind_text on m_keyvalue_.first Error on. %s"), sqlite3_errmsg(g_db));
        }
        index1 = sqlite3_bind_parameter_index(conStat, "@pa3");
        strYearT.ToLong(&ltmp);
        if(sqlite3_bind_int(conStat, index1, ltmp)!=SQLITE_OK) {
            wxLogDebug(_T("sqlite3_bind_text on m_keyvalue_.first Error on. %s"), sqlite3_errmsg(g_db));
        }
        index1 = sqlite3_bind_parameter_index(conStat, "@pa4");
        strMonthT.ToLong(&ltmp);
        if(sqlite3_bind_int(conStat, index1, ltmp)!=SQLITE_OK) {
            wxLogDebug(_T("sqlite3_bind_text on m_keyvalue_.first Error on. %s"), sqlite3_errmsg(g_db));
        }
        if(sqlite3_step(conStat)==SQLITE_ROW) {
            if(sqlite3_column_text(conStat,0)!=NULL) {
                wexpend=sqlite3_column_double(conStat,0);
                eexpend=sqlite3_column_double(conStat,1);
                sumexpend=sqlite3_column_double(conStat,2);
                csStat=wxString::Format(_T("总水费:%f,总电费:%f,总房租:%f\r\n"),wexpend,eexpend,sumexpend);
            }
        }
    } else {
        wxLogDebug(_T("Error on sqlite3_prepare_v2: %s"), sqlite3_errmsg(g_db));
    }
    if (sqlite3_finalize(conStat) != SQLITE_OK) {
        wxLogDebug(_T("Error on sqlite3_finalize: %s"), sqlite3_errmsg(g_db));
    }
    pText=wxDynamicCast(FindWindowById(IDC_EDIT_STATIC),wxTextCtrl);
    pText->SetValue(csStat);
    wxLogDebug(_T("OnBnClickedBtnSearch"));
}

void CDlgReportRent::OnBnClickedBtnExit(wxCommandEvent& event)
{
    Close();
    wxLogDebug(_T("OnBnClickedBtnExit"));
}

void CDlgReportRent::ShowData()
{
    wxListCtrl *pList=wxDynamicCast(FindWindowById(IDC_LIST),wxListCtrl);
    int itemcount=pList->GetItemCount();
    if(itemcount<=0) {
        return;
    }

    vector<pair<double,double> >wpri,epri,total;
    wxString strtmp;
    double dtime,depri,dwpri,dtotal;
    for (int n = 0; n < itemcount; n++) {
        strtmp=pList->GetItemText(n,1);
        long lyear,lmonth;
        strtmp=strtmp.SubString(0,strtmp.Find(_T("年"))-1);
        wxLogDebug(_T("1 %s"),strtmp);
        strtmp.ToLong(&lyear);
        strtmp=pList->GetItemText(n,1);
        strtmp=strtmp.SubString(strtmp.Find(_T("年"))+1,strtmp.Find(_T("月"))-1);
        wxLogDebug(_T("2 %s"),strtmp);
        strtmp.ToLong(&lmonth);
        strtmp=wxString::Format(_T("%d%02d"),lyear,lmonth);
        wxLogDebug(_T("3 %s"),strtmp);
        strtmp.ToDouble(&dtime);
        pList->GetItemText(n,4).ToDouble(&dwpri);
        pList->GetItemText(n,6).ToDouble(&depri);
        pList->GetItemText(n,7).ToDouble(&dtotal);
        wpri.push_back(std::make_pair(dtime,dwpri));
        epri.push_back(std::make_pair(dtime,depri));
        total.push_back(std::make_pair(dtime,dtotal));
    }
    double *wpri_data=NULL,*epri_data=NULL,*total_data=NULL;
    if(wpri.size()>0) {
        wxASSERT(wpri.size()==epri.size() || wpri.size() == total.size());
        wpri_data=new double[wpri.size()*2];
        epri_data=new double[wpri.size()*2];
        total_data=new double[wpri.size()*2];
        for(size_t i=0; i<wpri.size(); ++i) {
            wpri_data[i*2]  =wpri[i].first;
            wpri_data[i*2+1]=wpri[i].second;
            epri_data[i*2]  =epri[i].first;
            epri_data[i*2+1]=epri[i].second;
            total_data[i*2]  =total[i].first;
            total_data[i*2+1]=total[i].second;
        }
    }
    // first step: create plot
    XYPlot *plot = new XYPlot();

    // create dataset
    XYSimpleDataset *dataset = new XYSimpleDataset();

    // add two series
    if(wpri_data && epri_data && total_data) {
        dataset->AddSerie((double *) wpri_data, wpri.size());
        dataset->SetSerieName(dataset->GetSerieCount()-1, wxT("水费"));
        dataset->AddSerie((double *) epri_data, epri.size());
        dataset->SetSerieName(dataset->GetSerieCount()-1, wxT("电费"));
        dataset->AddSerie((double *) total_data, total.size());
        dataset->SetSerieName(dataset->GetSerieCount()-1, wxT("总房租"));
    }

    // create line renderer and set it to dataset
    XYLineRenderer *renderer = new XYLineRenderer();
    dataset->SetRenderer(renderer);

    // add our dataset to plot
    plot->AddDataset(dataset);

    // create left and bottom number axes
    NumberAxis *leftAxis = new NumberAxis(AXIS_LEFT);
    NumberAxis *bottomAxis = new NumberAxis(AXIS_BOTTOM);

    // add axes to plot
    plot->AddAxis(leftAxis);
    plot->AddAxis(bottomAxis);

    // link axes and dataset
    plot->LinkDataVerticalAxis(0, 0);
    plot->LinkDataHorizontalAxis(0, 0);

    // set serie names to be displayed on legend

    // set legend
    plot->SetLegend(new Legend(wxCENTER, wxRIGHT));

    Chart *chart = new Chart(plot, _T("趋势图"));
    chartpanel_->SetChart(chart);
    delete []wpri_data;
    delete []epri_data;
    delete []total_data;
}

void CDlgReportRent::OnTimer(wxTimerEvent& event)
{
    wxTimer& timer=event.GetTimer();
    if(timer.GetId()==IDC_TIMER_SEC) {
        ShowData();//显示数据
    }
}
